import { request, get } from '@ajax'
import { loginOut } from '@u/request'
import {router} from 'umi'
import { message } from 'antd'
import md5 from 'md5'
import { formatAuthMenu } from '@u/utils-cjy'
import {authRoutes} from '../../config/routers'  // 全部的权限路由
import config from '../../config/dev'

const {noAuth}=config
const jsEncrypt=window.JSEncrypt
const localStore=window.store

export default {
  namespace: 'login',
  state: {
    isLogin: noAuth?true:!!localStore.get('token'),
    userInfo: {},   // 用户信息
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload }
    },
  },
  effects: {
    * login({val, location}, {put}) {
      let firstHand = yield request('/login/token/firstHandshake', {
        method: 'post',
      })
      if (firstHand.code === '111') {
        const {requestCode, publicKey} = firstHand.data
        localStore.set('requestCode', requestCode)
        let encryptor = new jsEncrypt()
        encryptor.setPublicKey(publicKey)
        let rsaPassWord = encryptor.encrypt(md5(val.password))
        let token = yield request('/login/token/issue', {
          method: 'post',
          data: {
            username: val.username,
            password: rsaPassWord,
            applyType: 10,
            requestCode,
          },
          requestType: 'form'
        })
        if (token.code === '113') {
          yield localStore.set('token', token.data)
          yield put({
            type: 'save',
            payload: {
              isLogin: true,
            },
          })
          const {state}=location
          yield router.replace(state ? `${state.from.pathname}${state.from.search}` : '/')
        }else {
          message.error(token.codeMessage)
        }
      }
    },
    * getUserInfo(e, {put}) {
      let res
      if (noAuth){
        res = {success: true, data: {roleEnSet: ['SUPER_ADMIN']}}
      } else {
        res = yield get('/user')
      }
      if (res.success) {
        let data = res.data
        // 在这里产生用户的权限路由
        const {roleEnSet} = data
        // console.log(roleEnSet)
        let menuList=formatAuthMenu(authRoutes, roleEnSet) // 过滤后的菜单列表
        yield put({
          type: 'save',
          payload: {
            userInfo: data
          }
        })
        yield put({
          type: 'menuList/save',
          payload: {
            menuList
          }
        })
      }
    },
    * loginOut(e, {put}) {
      yield loginOut('退出成功')
      yield put({
        type: 'save',
        payload: {
          userInfo: {},
        }
      })
    }
  }
}
